package com.yin.myproject;

import com.yin.myproject.core.ScheduleTask;
import com.yin.myproject.util.ApplicationContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Eason
 * @create 2018-04-08 14:19
 **/
public class ConsoleManager {
    private ConsoleManager() {
    }

    private static final Logger LOG = LoggerFactory.getLogger(ConsoleManager.class);

    // 调度管理实例
    private static ZKScheduleManager scheduleManager;

    public static ZKScheduleManager getScheduleManager() {
        if (null == ConsoleManager.scheduleManager) {
            synchronized (ConsoleManager.class) {
                ConsoleManager.scheduleManager = ApplicationContextUtil.getBean(ZKScheduleManager.class);
            }
        }
        return ConsoleManager.scheduleManager;
    }

    /**
     * 添加任务
     *
     * @param scheduleTask
     */
    public static void addScheduleTask(ScheduleTask scheduleTask) {
        try {
            ConsoleManager.getScheduleManager().getScheduleDataManager().addTask(scheduleTask);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /**
     * 更新任务
     *
     * @param scheduleTask
     */
    public static void updateScheduleTask(ScheduleTask scheduleTask) {
        try {
            ConsoleManager.getScheduleManager().getScheduleDataManager().createAndUpdateTask(scheduleTask);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /**
     * 删除任务
     *
     * @param scheduleTask
     */
    public static void delScheduleTask(ScheduleTask scheduleTask) {
        try {
            ConsoleManager.getScheduleManager().getScheduleDataManager().delTask(scheduleTask);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /**
     * 查询任务列表
     *
     * @return
     */
    public static List<ScheduleTask> queryScheduleTask() {
        List<ScheduleTask> scheduleTasks = new ArrayList<>();
        try {
            List<ScheduleTask> tasks = ConsoleManager.getScheduleManager().getScheduleDataManager().selectTask();
            scheduleTasks.addAll(tasks);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return scheduleTasks;
    }

    /**
     * 检查任务是否存在
     *
     * @param scheduleTask
     * @return
     * @throws Exception
     */
    public static boolean isExistsTask(ScheduleTask scheduleTask) throws Exception {
        return ConsoleManager.getScheduleManager().getScheduleDataManager().isExistsTask(scheduleTask);
    }

}
